/*
 * MIT License
 *
 * Copyright (c) 2024 org.zzz (https://gitee.com/frostforest)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.zzz.pcdc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.zzz.pcdc.PcdcUtils.getFirst;

class PcdcIndexMapBuilder {
    public static final String COL_INDEX_NAME = "INDEX_NAME";
    public static final String COL_COLUMN_NAME = "COLUMN_NAME";
    private static final Logger LOGGER = LoggerFactory.getLogger(PcdcIndexMapBuilder.class);
    final DataSource dataSource;

    public PcdcIndexMapBuilder(DataSource dataSource) {
        this.dataSource = dataSource;
    }


    public Map<String, List<String>> buildIndexMap(String tableName) throws SQLException {
        Map<String, List<String>> indexMap = new java.util.HashMap<>();
        try (Connection conn = dataSource.getConnection()) {
            conn.setAutoCommit(true);
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery("show index from `%s`".formatted(tableName.strip()));
            while (rs.next()) {
                String indexName = rs.getString("Key_name");
                String columnName = rs.getString("Column_name");
                int seqInIndex = rs.getInt("Seq_in_index");
                boolean visible = "YES".equalsIgnoreCase(rs.getString("Visible"));
                if (visible) {
                    List<String> indexColumns = indexMap.computeIfAbsent(indexName,
                            k -> new ArrayList<>());
                    for (int i = indexColumns.size(); i < seqInIndex; i++) {
                        indexColumns.add("");
                    }
                    indexColumns.set(seqInIndex - 1, columnName);
                }
            }
        }
        return indexMap;
    }

    public Map<String, List<String>> buildCanUseIndexMap(String tableName) throws SQLException {
        Map<String, List<String>> canUseIndexMap = new java.util.HashMap<>();
        Map<String, List<String>> indexMap = buildIndexMap(tableName);
        indexMap.entrySet().forEach(entry -> {
            String indexName = entry.getKey();
            List<String> indexColumns = entry.getValue();
            String indexColDefine = indexColumns.stream().map(String::strip)
                    .map(String::toLowerCase)
                    .collect(Collectors.joining(","));
            int i = indexColDefine.length();
            String prefixIndexColumn;
            do {
                prefixIndexColumn = indexColDefine.substring(0, i);
                List<String> indexNameList = canUseIndexMap.computeIfAbsent(prefixIndexColumn,
                        k -> new ArrayList<>());
                if (i == indexColDefine.length()) {
                    indexNameList.add(0, indexName);
                } else {
                    if (!indexNameList.isEmpty()) {
                        LOGGER.warn("Found a redundant prefix index. {} contains {}.for table {}",
                                indexName,
                                getFirst(indexNameList),
                                tableName);
                    }
                    indexNameList.add(indexName);
                }
            } while ((i = prefixIndexColumn.lastIndexOf(",")) > 0);
        });
        return Collections.unmodifiableMap(canUseIndexMap);
    }
}
